package com.alex.common.security;

import java.io.IOException;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.util.HtmlUtils;

import com.alex.common.persistent.UserDao;
import com.alex.common.security.domain.User;
import com.alex.common.security.domain.User.Authority;
import com.alex.common.tools.CookieUtils;

public class SimpleAuthor {
	private static SimpleAuthor me = new SimpleAuthor();

	public static SimpleAuthor getInstance() {
		return me;
	}

	public static final String S_USERNAME = "S_USERNAME";

	public static final String S_AUTHORITY = "S_AUTHORITY";

	// Like "kthq 25d55ad283aa400af464c76d713c07ad"
	public static final String S_COOKIE_TICKET = "SCT";

	private boolean isWhat(Authority authority, HttpServletRequest request) {
		Integer s_authority = (Integer) request.getSession().getAttribute(
				S_AUTHORITY);
		if (s_authority != null && s_authority >= authority.ordinal()) {
			return true;
		}

		CookieUtils cookieU = new CookieUtils(request);
		Cookie cookie = cookieU.get(S_COOKIE_TICKET);
		if (cookie != null) {
			if (cookie.getValue() != null
					&& cookie.getValue().split(" ").length == 2) {
				// has ticket
				String[] user_pass = cookie.getValue().split(" ");
				User user = UserDao.getInstance().find(user_pass[0]);

				// check ticket
				if (user.getPassword().equals(user_pass[1])
						&& user.getAuthority() >= authority.ordinal()) {
					{
						// set username and authority to session
						request.getSession().setAttribute(
								SimpleAuthor.S_USERNAME, user.getUsername());
						request.getSession().setAttribute(
								SimpleAuthor.S_AUTHORITY, user.getAuthority());
					}
					return true;
				}

			}
		}
		return false;
	}

	public String getUsername(HttpServletRequest request) {
		if (isWhat(Authority.USER, request)) {
			return (String) request.getSession().getAttribute(S_USERNAME);
		} else {
			return null;
		}
	}

	public boolean needAdmin(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		if (!isWhat(Authority.ADMIN, request)) {
			String ref = HtmlUtils.htmlEscape(request.getRequestURI()
					+ (request.getQueryString() == null ? "" : "?"
							+ request.getQueryString()));
			response.sendRedirect("/login?ref=" + ref);
			return false;
		}
		return true;
	}

	public boolean needUser(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		if (!isWhat(Authority.USER, request)) {
			String ref = HtmlUtils.htmlEscape(request.getRequestURI()
					+ (request.getQueryString() == null ? "" : "?"
							+ request.getQueryString()));
			response.sendRedirect("/login?ref=" + ref);
			return false;
		}
		return true;
	}
}
